package com.party.admin.web.controller.sign;

import com.google.common.base.Strings;
import com.party.admin.biz.file.FileBizService;
import com.party.admin.biz.sign.SignProjectBizService;
import com.party.admin.utils.RealmUtils;
import com.party.admin.web.dto.AjaxResult;
import com.party.admin.web.dto.input.common.CommonInput;
import com.party.admin.web.dto.input.sign.SignProjectInput;
import com.party.admin.web.dto.output.sign.SignProjectOutput;
import com.party.api.dto.wechat.requst.XcxQrCodeRequest;
import com.party.common.constant.Constant;
import com.party.common.paging.Page;
import com.party.common.utils.StringUtils;
import com.party.core.model.YesNoStatus;
import com.party.core.model.sign.SignProject;
import com.party.core.model.sign.SignProjectAuthor;
import com.party.core.model.wechatPlatform.WechatOpenMember;
import com.party.core.service.sign.ISignProjectService;
import com.party.core.service.wechatPlatform.IWechatOpenMemberService;
import com.party.core.utils.MyBeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Map;

/**
 * 签到项目控制器
 * Created by wei.li
 *
 * @date 2017/6/6 0006
 * @time 10:11
 */

@Controller
@RequestMapping(value = "sign/project")
public class SignProjectController {

    @Autowired
    private ISignProjectService signProjectService;

    @Autowired
    private SignProjectBizService signProjectBizService;

    @Autowired
    private FileBizService fileBizService;

    @Autowired
    private IWechatOpenMemberService wechatOpenMemberService;


    Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 签到信息列表
     * @param signProjectAuthor 签到信息
     * @param page 分页参数
     * @return 列表信息
     */
    @RequestMapping(value = "list")
    public ModelAndView list(SignProjectAuthor signProjectAuthor, Page page, CommonInput commonInput) {
        ModelAndView modelAndView = new ModelAndView("sign/signProjectList");
        Map<String, Object> params = CommonInput.appendParams(commonInput);

        List<SignProjectOutput> list = signProjectBizService.list(signProjectAuthor, page, params);
        modelAndView.addObject("list", list);
        modelAndView.addObject("page", page);
        modelAndView.addObject("project", signProjectAuthor);
        modelAndView.addObject("input", commonInput);
        return modelAndView;
    }

    /**
     * 签到信息试图
     * @param id 编号
     * @return 交互信息
     */
    @RequestMapping(value = "view")
    public ModelAndView view(String id){
        ModelAndView modelAndView = new ModelAndView("sign/signProjectView");
        SignProject signProject;
        if (Strings.isNullOrEmpty(id)){
            signProject = new SignProject();
            signProject.setApplyCheck(YesNoStatus.NO.getCode());
            signProject.setRankShow(YesNoStatus.YES.getCode());
            signProject.setGradeCheck(YesNoStatus.NO.getCode());
        }
        else {
            signProject = signProjectService.get(id);
            if (StringUtils.isNotEmpty(signProject.getRule())) {
                String content = StringUtils.unescapeHtml4Video2Iframe(signProject.getRule());
                signProject.setRule(content);
            }
        }
        modelAndView.addObject("signProject", signProject);
        return modelAndView;
    }


    /**
     * 保存签到信息
     * @param signProjectInput 签到项目
     * @return 交互数据
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "save")
    public AjaxResult save(SignProjectInput signProjectInput) {
        try {
            AjaxResult ajaxResult = new AjaxResult();
            SignProject signProject = SignProjectInput.transform(signProjectInput);
            String memberId = Strings.isNullOrEmpty(signProjectInput.getCreateBy()) ? RealmUtils.getCurrentUser().getId() : signProjectInput.getCreateBy();
            if (StringUtils.isNotEmpty(signProject.getRule())) {
                String content = StringUtils.escapeHtml4Iframe2Video(signProject.getRule().trim());
                signProject.setRule(content);
            }
            if (Strings.isNullOrEmpty(signProjectInput.getId())) {
                signProject.setCreateBy(memberId);
                signProject.setUpdateBy(memberId);

                signProjectService.insert(signProject);
            } else {
                SignProject dbProject = signProjectService.get(signProjectInput.getId());
                MyBeanUtils.copyBeanNotNull2Bean(signProject, dbProject);
                dbProject.setUpdateBy(memberId);
                signProjectService.update(dbProject);

                memberId = dbProject.getCreateBy();
            }

            try {
                WechatOpenMember openMember = wechatOpenMemberService.findByType(Constant.WECHAT_ACCOUNT_TYPE_SYSTEM_XCX_SIGN);
                XcxQrCodeRequest qrCodeRequest = new XcxQrCodeRequest();
                qrCodeRequest.setPage("pages/pro/index");
                qrCodeRequest.setScene(signProject.getId());
                String filePath = fileBizService.getUploadCIPath(memberId, "signProject");
                fileBizService.uploadCloudOut(signProject.getId(), filePath, qrCodeRequest, openMember.getAuthorizerAccessToken(), 1);
            } catch (Exception e) {
                logger.error("生成小程序码异常", e);
            }
            ajaxResult.setSuccess(true);
            return ajaxResult;
        } catch (Exception e) {
            logger.error("保存运动打卡项目异常", e);
            return AjaxResult.error("保存项目异常");
        }
    }

    /**
     * 删除签到项目
     * @param id 编号
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "delete")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult delete(String id){
        boolean result = signProjectBizService.deleteProjectBiz(id);
        if (result) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error("删除失败");
        }
    }

    @ResponseBody
    @RequestMapping("initQrCode")
	public AjaxResult initQrCode() {
		List<SignProject> list = signProjectService.list(new SignProject());
		for (SignProject projectAuthor : list) {
			String filePath = fileBizService.getUploadCIPath(projectAuthor.getCreateBy(), "signProject");

			String localPath = projectAuthor.getCreateBy() + "/signProject/";
			String content = "sign/sign_pro.html?id=" + projectAuthor.getId();
			fileBizService.uploadCloudOut(projectAuthor.getId(), filePath, localPath, projectAuthor.getId(), content, projectAuthor.getCreateBy());
		}
		return AjaxResult.success();
	}

    /**
     * 初始化小程序二维码
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("initXcxQrCode")
    public AjaxResult initXcxQrCode() {
        WechatOpenMember openMember = wechatOpenMemberService.findByType(Constant.WECHAT_ACCOUNT_TYPE_SYSTEM_XCX_SIGN);
        List<SignProject> list = signProjectService.list(new SignProject());
        for (SignProject signProject : list) {
            String filePath = fileBizService.getUploadCIPath(signProject.getCreateBy(), "signProject");
            XcxQrCodeRequest qrCodeRequest = new XcxQrCodeRequest();
            qrCodeRequest.setPage("pages/pro/index");
            qrCodeRequest.setScene(signProject.getId());
            fileBizService.uploadCloudOut(signProject.getId(), filePath, qrCodeRequest, openMember.getAuthorizerAccessToken(), 0);
        }
        return AjaxResult.success();
    }

    /**
     * 校正项目数据
     *
     * @param projectId 项目id
     * @return
     */
    @ResponseBody
    @RequestMapping("reviseProject")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult reviseProject(String projectId) {
        boolean result = signProjectBizService.reviseProject(projectId);
        if (result) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error("校正失败");
        }
    }

    /**
     * 生成小程序吗
     *
     * @param projectId 项目id
     * @return
     */
    @ResponseBody
    @RequestMapping("checkXcxQrCode")
    public AjaxResult checkXcxQrCode(String projectId) {
        if (StringUtils.isEmpty(projectId)) {
            return AjaxResult.error("项目id不能为空");
        }
        try {
            WechatOpenMember openMember = wechatOpenMemberService.findByType(Constant.WECHAT_ACCOUNT_TYPE_SYSTEM_XCX_SIGN);
            SignProject signProject = signProjectService.get(projectId);
            String filePath = fileBizService.getUploadCIPath(signProject.getCreateBy(), "signProject");
            XcxQrCodeRequest qrCodeRequest = new XcxQrCodeRequest();
            qrCodeRequest.setPage("pages/pro/index");
            qrCodeRequest.setScene(signProject.getId());
            String result = fileBizService.uploadCloudOut(signProject.getId(), filePath, qrCodeRequest, openMember.getAuthorizerAccessToken(), 0);
            if (StringUtils.isEmpty(result)) {
                throw new Exception("生成小程序码异常");
            }
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("生成小程序码异常", e);
            return AjaxResult.error("异常");
        }
    }
}
